package com.house.service;

import com.house.entity.UserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserLogin userLogin= userService.findByAdmin(s);
        if(null==userLogin)
            throw new UsernameNotFoundException("无此用户");
        List<GrantedAuthority> authorities=new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_user"));
        if(userLogin.getUsertype()>=1){
            authorities.add(new SimpleGrantedAuthority("ROLE_admin"));
        }if(userLogin.getUsertype()==2){
            authorities.add(new SimpleGrantedAuthority("ROLE_sadmin"));
        }
        return new User(userLogin.getAdmin(),userLogin.getPassword(),authorities);
    }
}
